using System.Collections.Generic;
using CGF;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class LoginUIUsername : MonoBehaviour
{
    public InputField inputUsername, inputPasswd;

    private const string InputCacheKey = "InputUsername";

    private void Awake()
    {
        inputUsername.text = PlayerPrefs.GetString(InputCacheKey);
    }

    public async void Login()
    {
        if (inputUsername.text.Contains(" "))
        {
            Dialog.Alert(CommAssets.instance.I18N_account_canot_space);
            return;
        }
        if (inputUsername.text.Length < 5)
        {
            Dialog.Alert(CommAssets.instance.I18N_username_length_invalid.Replace("{num}", "5"));
            return;
        }
        if (StringHelper.IsContainsSpecialChar(inputUsername.text))
        {
            Dialog.Alert(CommAssets.instance.I18N_cannot_inc_spec_char);
            return;
        }
        if (!StringHelper.IsNumberAndLetter(inputPasswd.text))
        {
            Dialog.Alert(CommAssets.instance.I18N_passwd_must_letter8);
            return;
        }
        PlayerPrefs.SetString(InputCacheKey, inputUsername.text);

        JsonData data = new JsonData();
        data["user_name"] = inputUsername.text;
        data["password"] = inputPasswd.text;
        Dictionary<string, Network.CustomPopupMsgs> customMsg = new Dictionary<string, Network.CustomPopupMsgs>()
        {
            {
                "Invalid userName or password", new Network.CustomPopupMsgs()
                {
                    msg = RootComponent.instance.GetComponent<LoginUI>().I18N_account_not_exist,
                }
            }
        };
        Network.Res res = await Network.Post("/v1/oauth/login", data, customPopupMsgs: customMsg);
        if (res.success)
        {
            RootComponent.instance.GetComponent<LoginUI>().OnLogin(res.jsonData);
        }
    }
}
